#!/usr/bin/env bun
/**
 * 使用 Puppeteer 引擎进行转换测试
 * 对比 Playwright 方案的稳定性
 */

import { promises as fs } from 'fs';
import path, { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { markdownFileToDocx } from '../../../../src/tools/convert/markdown-to-docx.js';
import { markdownFileToPdf } from '../../../../src/tools/convert/markdown-to-pdf.js';

// 强制使用 Puppeteer 引擎
process.env.BROWSER_ENGINE = 'puppeteer';
// 强制使用系统 Chrome，以对齐 Playwright 与 Puppeteer 的内核
process.env.BROWSER_CHANNEL = process.env.BROWSER_CHANNEL || 'chrome';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const sourceDir = join(__dirname, 'md');
const targetDir = join(__dirname, '..', '..', '..', 'out');

async function ensureTargetDir(dir: string): Promise<void> {
  await fs.mkdir(dir, { recursive: true });
}

async function getAllMarkdownFiles(dir: string): Promise<string[]> {
  const files = await fs.readdir(dir);
  return files.filter(f => f.endsWith('.md')).map(f => path.join(dir, f));
}

async function convertFile(sourceFile: string, testRound: number): Promise<void> {
  const fileName = path.basename(sourceFile, '.md');
  const pdfPath = path.join(targetDir, `${fileName}-puppeteer-round${testRound}.pdf`);
  const docxPath = path.join(targetDir, `${fileName}-puppeteer-round${testRound}.docx`);

  console.log(`\n🔄 [Puppeteer-轮次${testRound}] 开始转换 ${fileName}`);

  try {
    console.log('  📄 正在生成 PDF...');
    const t0 = Date.now();
    const pdfResult = await markdownFileToPdf(sourceFile, pdfPath, {
      format: 'A4',
      printBackground: true,
      title: `${fileName} - Puppeteer 轮次${testRound}`,
    });
    console.log(
      `  ✅ PDF 成功 (${Date.now() - t0}ms): ${pdfResult.outputPath} (${(
        pdfResult.size! / 1024
      ).toFixed(1)} KB)`
    );
  } catch (e) {
    console.error('  ❌ PDF 失败:', e instanceof Error ? e.message : String(e));
  }

  try {
    console.log('  📝 正在生成 DOCX（包含Mermaid）...');
    const t1 = Date.now();
    // 直接使用markdownFileToDocx保留所有内容包括Mermaid
    const docxResult = await markdownFileToDocx(sourceFile, docxPath, {
      title: `${fileName} - Puppeteer 轮次${testRound}`,
      creator: 'Puppeteer 测试',
      chineseFont: 'Microsoft YaHei',
    });
    console.log(
      `  ✅ DOCX 成功 (${Date.now() - t1}ms): ${docxResult.outputPath} (${(
        docxResult.size! / 1024
      ).toFixed(1)} KB)`
    );
  } catch (e) {
    console.error('  ❌ DOCX 失败:', e instanceof Error ? e.message : String(e));
  }
}

async function main() {
  console.log('🚀 使用 Puppeteer 进行转换对比测试...');
  await ensureTargetDir(targetDir);
  const files = await getAllMarkdownFiles(sourceDir);
  if (files.length === 0) {
    console.log('❌ 未找到 markdown 文件');
    return;
  }

  // 优先 comprehensive-test.md
  const priority = files.find(f => path.basename(f) === 'comprehensive-test.md');
  const ordered = priority ? [priority, ...files.filter(f => f !== priority)] : files;

  const rounds = 2; // 先跑2轮
  for (let r = 1; r <= rounds; r++) {
    console.log(`\n🔥 ========== Puppeteer 测试轮次 ${r} ==========`);
    for (const f of ordered) {
      await convertFile(f, r);
      await new Promise(res => setTimeout(res, 800));
    }
  }

  console.log('\n🎉 Puppeteer 测试完成');
}

if (import.meta.main) {
  main().catch(console.error);
}
